<template>
  <template v-for="column in cols" :key="column.key">
    <!-- selection 列渲染 -->
    <ElTableColumn v-if="column.type === 'selection'" :selectable="column.selectable || (row => !row._disabled)"
      :type="column.type" :width="column.width" :fixed="column.fixed" :align="column.align" v-bind="column">
      <template v-if="column.renderSelection" #default="scope">
        <component :is="column.renderSelection(scope)" />
      </template>
    </ElTableColumn>

    <ElTableColumn v-else :prop="column.key" :label="column.title" :width="column.width" :sortable="column.sortable"
      :min-width="column.minWidth" :fixed="column.fixed" :align="column.align" :class-name="column.className"
      v-bind="column">
      <!-- 自定义列头渲染 -->
      <template v-if="column.renderColumnHeader" #header="scope">
        <component :is="column.renderColumnHeader(h, {
          ...scope,
          column,
          index: scope.$index
        })
          " />
      </template>

      <!-- 自定义渲染方式、插槽 -->
      <template v-if="column.render || column.slot" #default="scope">
        <component v-if="column.render" :is="column.render(h, { ...scope, column, index: scope.$index })" />

        <component v-else-if="column.slot && slots?.[column.slot]" :is="renderSlot(column.slot, scope)" />
      </template>
    </ElTableColumn>
  </template>
</template>

<script setup lang="ts">
import { h } from 'vue'
import { ElTableColumn } from 'element-plus'

const { cols = [], slots = {} } = defineProps(['cols', 'slots'])

const renderSlot = (slotName, scope) => {
  const slotProps = {
    row: scope.row,
    column: scope.column,
    $index: scope.$index
  }
  return () => slots[slotName]?.(slotProps) || null
}
</script>
